package web.sso.common.collections;

import web.sso.common.throwable.ConstructorNotAvailableError;

import java.util.*;
import java.util.function.Function;

/**
 * DATE: 2020/1/19
 * TIME: 5:03 下午
 *
 * @author：huangliming
 */
public class Lists extends Collections {
    /**
     * 构造器不允许调用
     * 抛出异常目的是防止反射获取
     */
    private Lists() {
        throw new ConstructorNotAvailableError(Lists.class);
    }

    /**
     * 重映射List
     * @param list
     * @param mapper
     * @return
     */
    public static <T, R> ListTransfer<T, R> reList(List<T> list, Function<T, R> mapper) {
        return new ListTransfer<>(list, mapper);
    }

    /**
     * 重映射list，不修改元素类型
     * @param list
     * @param <T>
     * @return
     */
    public static <T> ListTransfer<T, T> reList(List<T> list) {
        return reList(list, e -> e);
    }

    /**
     * 从一个Set生成List
     * @param set
     * @return
     */
    public static <T, R> ListTransfer<T, R> fromSet(Set<T> set, Function<T, R> mapper) {
        return new ListTransfer<>(set, mapper);
    }

    /**
     * 从一个Set生成一个list，不修改元素类型
     * @param set
     * @param <T>
     * @return
     */
    public static <T> ListTransfer<T, T> fromSet(Set<T> set) {
        return fromSet(set, e -> e);
    }

    /**
     * 重映射实现类
     */
    public static class ListTransfer<T, R> {

        private Collection<T> collection;
        private Function<T, R> mapper;

        ListTransfer(Collection<T> collection, Function<T, R> mapper) {
            this.collection = collection;
            this.mapper = mapper;
        }

        /**
         * 将实例重新映射为ArrayList
         * @return
         */
        public ArrayList<R> arrayList() {
            ArrayList<R> aList = new ArrayList<>(collection.size());
            reBuild(aList);
            return aList;
        }

        /**
         * 将实例重映射为LinkedList
         * @return
         */
        public LinkedList<R> linkedList() {
            LinkedList<R> aList = new LinkedList<>();
            reBuild(aList);
            return aList;
        }

        /**
         * 将实例重映射为线程安全的List实例
         * @return
         */
        public List<R> synchronizedList() {
            return java.util.Collections.synchronizedList(arrayList());
        }

        /**
         * 将实例转换为Vector实例
         * @return
         */
        public Vector<R> vector() {
            Vector<R> rVector = new Vector<>(collection.size());
            reBuild(rVector);
            return rVector;
        }

        /**
         * 转换核心代码
         * @param reCollection
         */
        private void reBuild(Collection<R> reCollection) {
            collection.forEach(e -> reCollection.add(mapper.apply(e)));
        }
    }
}
